package com.ycl.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycl.bookstore.common.Result;
import com.ycl.bookstore.mapper.RechargeRecordMapper;
import com.ycl.bookstore.pojo.Balance;
import com.ycl.bookstore.pojo.RechargeRecord;
import com.ycl.bookstore.service.BalanceService;
import com.ycl.bookstore.mapper.BalanceMapper;
import com.ycl.bookstore.utils.MyThreadLocal;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import static com.ycl.bookstore.utils.RedisConstants.RECORD_LIST_KEY;
import static com.ycl.bookstore.utils.RedisConstants.USER_BALANCE_KEY;

/**
 *
 */
@Service
public class BalanceServiceImpl extends ServiceImpl<BalanceMapper, Balance>
        implements BalanceService {

    @Resource
    private BalanceMapper balanceMapper;

    @Resource
    private RechargeRecordMapper rechargeRecordMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取用户的余额
     *
     * @return
     */
    @Override
    public Result getUserBalance() {
        Map<String, Object> data = new HashMap<>();
        // 获取用户的id
        Long userId = MyThreadLocal.getUser().getId();
        // 看redis中用户是否存在用户的余额
        Object balance = stringRedisTemplate.opsForHash().get(USER_BALANCE_KEY, userId.toString());
        if (balance == null) {
            LambdaQueryWrapper<Balance> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Balance::getUserId, userId);
            // 从数据库查询用户的余额  将用户的余额存入redis中
            balance = balanceMapper.selectOne(wrapper).getBalance().toString();
            stringRedisTemplate.opsForHash().put(USER_BALANCE_KEY, userId.toString(), balance);
        }
        data.put("balance", balance);
        return Result.success(data);
    }

    /**
     * 充值金额
     * 因为有两张表的处理  因此要加入事务
     *
     * @return
     */
    @Override
    @Transactional
    public Result rechargeMoney(BigDecimal money) {
        try {
            //获取用户id
            Long userId = MyThreadLocal.getUser().getId();
            Balance balance = balanceMapper.selectById(userId);
            balance.setBalance(balance.getBalance().add(money));
            // 更新用户金额
            balanceMapper.updateById(balance);
            // 增加用户充值记录
            addRecord(userId, money);
            // 测试异常
            // String s=null;
            // s.length();
            //删除redis的用户金额缓存和用户充值记录缓存
            stringRedisTemplate.opsForHash().delete(USER_BALANCE_KEY, userId + "");
            stringRedisTemplate.delete(RECORD_LIST_KEY + userId);
            return Result.success();
        } catch (Exception e) {
            return Result.fail("充值失败");
        }
    }

    public int addRecord(Long userId, BigDecimal money) {
        // 创建记录对象
        RechargeRecord record = new RechargeRecord();
        record.setUserId(userId);
        record.setMoney(money);
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        record.setRechargeTime(now);
        // 创建充值编号
        String recordId = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssS"));
        record.setRecordId(recordId);
        record.setStatus(1);
        int count = rechargeRecordMapper.insert(record);
        return count;
    }
}




